//
//  HQQMusicPlayer.m
//  HQQMusicPlayerDemo
//
//  Created by 黄强强 on 16/9/13.
//  Copyright © 2016年 黄强强. All rights reserved.
//

#import "HQQMusicPlayer.h"
#import <AVFoundation/AVFoundation.h>

@interface HQQMusicPlayer () <AVAudioPlayerDelegate>
/**
 *  播放器
 */
@property (nonatomic, strong) AVAudioPlayer *player;
@end

@implementation HQQMusicPlayer

+ (instancetype)sharedInstance
{
    static dispatch_once_t onceToken;
    static id instance = nil;
    dispatch_once(&onceToken, ^{
        instance = [[self alloc] init];
    });
    return instance;
}

- (void)playWithFilePath:(NSString *)filePath
{
    [self playBack];
    NSError *err = nil;
    
    NSURL *url = [NSURL fileURLWithPath:filePath];
    NSData *data = [NSData dataWithContentsOfURL:url options:0 error:&err];
    AVAudioPlayer *player = [[AVAudioPlayer alloc] initWithData:data error:nil];
    player.delegate = self;
    player.enableRate = YES;
    [player prepareToPlay];
    [player play];
    
    self.player = player;
}

- (void)play
{
    [self playWithFilePath:nil];
}

- (void)pause
{
    
}

/**
 *  后台播放
 */
- (void)playBack
{
    AVAudioSession *session = [AVAudioSession sharedInstance];
    [session setCategory:AVAudioSessionCategoryPlayback error:nil];
    [session setActive:YES error:nil];
}

#pragma mark - delegate

- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag
{
    NSLog(@"audioPlayerDidFinishPlaying");
}

@end
